package com.feimt.common;

import java.util.Random;

/**
 * @author 宋孟林
 * @date 2025-3-4
 */
public class CodeUtils {
    private static final int CODE_LENGTH_FOUR = 4;
    private static final int CODE_LENGTH_SIX = 6;
    private static final int MAX_FOUR_DIGIT = 9999;
    private static final int MAX_SIX_DIGIT = 999999;
    private static final int MIN_FOUR_DIGIT = 1000;
    private static final int MIN_SIX_DIGIT = 100000;

    /**
     * <p>实现生成随机的验证码，将指定长度length的作为生成验证码长度，然后调用random对象的nextInt方法来生成一个随机数
     * 如果随机数小于定义的最小四位或者六位验证码，就加上这个最小定义的验证码</p>
     * @param length 验证码长度
     * @return integer的验证码
     */
    public static Integer generateValidateCode(int length) {
        Random random = new Random();
        Integer code;
        if (length == CODE_LENGTH_FOUR) {
            code = random.nextInt(MAX_FOUR_DIGIT + 1);
            if (code < MIN_FOUR_DIGIT) {
                code += MIN_FOUR_DIGIT;
            }
        }else if (length == CODE_LENGTH_SIX) {
            code = random.nextInt(MAX_SIX_DIGIT + 1);
            if (code < MIN_SIX_DIGIT) {
                code += MIN_SIX_DIGIT;
            }
        }else {
            throw new IllegalArgumentException("只能生成 4 位或 6 位数字验证码");
        }
        return code;
    }

    /**
     * 随机生成指定长度字符串验证码
     * @param length 长度
     * @return 1
     */
    public static String generateValidateCode4String(int length){
        Random rdm = new Random();
        String hash1 = Integer.toHexString(rdm.nextInt());
        String capStr = hash1.substring(0, length);
        return capStr;
    }
}
